package xml;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashMap;

import logger.Logger;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public class IgnoreMJProvider {

	public static final IgnoreMJProvider INSTANCE = new IgnoreMJProvider();
	private HashMap<String, Object> ignore = new HashMap<>();
	private Object ob = new Object();
	
	private IgnoreMJProvider()
	{
		
		try
		{
			File f = new File("ignoreMJ.xml");
			if(!f.exists())
			{
				XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
				sortie.output(new Document(new Element("Ignorer")), new FileOutputStream("ignoreMJ.xml"));
				//f.createNewFile();
			}
			
			SAXBuilder sxb = new SAXBuilder();
			Document doc = sxb.build(f);
			for(Element el : doc.getRootElement().getChildren())
			{
				String ign = el.getAttributeValue("Name");
				ignore.put(ign, ob);
				
			}
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		saveAll();
	}
	
	public boolean isIgnored(String mj)
	{
		return ignore.containsKey(mj);
	}
	
	public Collection<String> getIgnores()
	{
		return ignore.keySet();
	}
	
	public void saveAll()
	{
		Element newRoot = new Element("ListeConfiance");
		
		for(String ign : getIgnores())
		{
			Element impE = new Element("Ignorer");
			impE.setAttribute(new Attribute("Name", ign));
			newRoot.addContent(impE);
		}
		
		enregistre(newRoot, "ignoreMJ.xml");
	}
	
	private static void enregistre(Element racine, String fichier)
	{
	   try
	   {
	      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
	      sortie.output(new Document(racine), new FileOutputStream(fichier));
	   }
	   catch (java.io.IOException e){
		   Logger.INSTANCE.logError(e);
	   }
	}
}

